import React, {useEffect, useState, useRef} from 'react'
import {
	Button,
	Space,
	message,
	Tag,
	Form,
	Row,
	Col,
	Input,
	Radio,
	Modal,
} from 'antd'

import {history, connect} from 'umi'
import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import Permissions from '@/components/Permissions'
import {
	getProcessPage,
	getOperationUpdate,
	postPhysicalDistribution,
	postCashBackDistribution,
	batchApproval,
} from '@/service/marketing/awardSettlement/processList'
import {getOrderType} from '@/service/marketing/commodity'
import {translateDataToTree} from '@/utils/common/index'
import {getMainCompanyList, getCompany} from '@/service/system/company'
import {formatDate} from '@/utils/common/dateFilter'
import {getAllCitys} from '@/service/common'
import {getDict} from '@/service/common/dict'
import ModalComponent from '../../commodityPlan/components/Modal'
import 'moment/locale/zh-cn'

const {TextArea} = Input
const formItemLayout = {
	labelCol: {flex: '110px'},
	wrapperCol: {flex: '1'},
}
const commodityPlan = (props: {user: any}) => {
	const {orgId} = props.user
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [total, setTotal] = useState(0)
	const [loading, setLoading] = useState(false)

	const [citysList, setCitysList] = useState([])
	const [orderType, setOrderType] = useState([])
	const [mainCompany, setMainCompanyList] = useState([])
	const [orgSource, setOrgSource] = useState<any>([])

	const [dataSourse, setDataSourse] = useState([])
	const [searchData, setSearchData] = useState({})
	const [formData, setFormData] = useState<any[]>([])
	const [checkData, setCheckData] = useState<any>([])
	const [checkProcessList, setCheckProcessList] = useState<any>([])

	// 批量返现
	const [isModalBackOpen, setIsModalBackOpen] = useState(false)
	// 批量已发放
	const [isModalIssuedOpen, setIsModalIssuedOpen] = useState(false)

	// 审核弹窗
	const [isToExamineView, setIsToExamineView] = useState(false)
	const [toExamineForm] = Form.useForm()

	const [dict, setDict] = useState({
		order_location: [],
		settlement_approval_status: [],
		physical_state: [],
		subsidy_mode: [],
	})
	// 字典查询
	useEffect(() => {
		// 初始化
		getDict(
			{
				dictKeys: [
					'order_location',
					'settlement_approval_status',
					'physical_state',
					'subsidy_mode',
				],
			},
			(res: any) => {
				setDict(res)
			},
		)
	}, [])

	// 获取主体数据
	const onMainCompanyeListFun = () => {
		getMainCompanyList().then((res: any) => {
			if (res?.success) {
				setMainCompanyList(res.data)
			}
		})
	}

	// 获取组织机构数据
	const onOrgFun = () => {
		getCompany({merchantId: orgId}).then((res: any) => {
			if (res?.success) {
				const list: any = translateDataToTree(res?.data)
				setOrgSource(list as any)
			}
		})
	}
	useEffect(() => {
		onOrgFun()
	}, [orgId])

	/** 获取城市列表 */
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.success) {
				setCitysList(() => res?.data)
			}
		})
	}

	/** 获取订单类型列表 */
	const getOrderTypeFun = () => {
		getOrderType().then((res: any) => {
			if (res?.success) {
				setOrderType(() => res?.data)
			}
		})
	}

	useEffect(() => {
		getCitysFun()
		getOrderTypeFun()
		onMainCompanyeListFun()
	}, [])

	// 获取表格数据
	const onListFun = () => {
		setLoading(true)
		getProcessPage({
			...params,
			...searchData,
		})
			.then((res: any) => {
				if (res?.success) {
					setCheckData([])
					setDataSourse(() => res?.data?.records)
					setTotal(() => res?.data?.total)
				}
				setLoading(false)
			})
			.catch(() => {
				setLoading(false)
			})
	}

	// 获取表格数据
	// 自定义一个初始不更新的hook
	const useUpdateEffect = (fn: Function, inputs: any[]) => {
		const didMountRef = useRef(false)
		useEffect(() => {
			if (didMountRef.current) fn()
			else didMountRef.current = true
		}, inputs)
	}

	// 使用自定义hook
	useUpdateEffect(onListFun, [params])

	// 备注编辑
	const onOperationUpdate = (id: string, remarks: string) => {
		getOperationUpdate({id, remarks})
			.then((res: any) => {
				if (res?.success) {
					message.success(res?.msg)
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}
	const columns: any = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text: any, record: any, index: any) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '补贴月份',
			dataIndex: 'subsidyMonth',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '提车月份',
			dataIndex: 'collectionMonth',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '城市名称',
			dataIndex: 'cityName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '所属主体名称',
			dataIndex: 'principalName',
			width: 150,
			align: 'center',
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '公司',
			dataIndex: 'corporateName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '司机姓名',
			dataIndex: 'driverName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '司机ID',
			dataIndex: 'driverId',
			align: 'center',
			width: 200,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '订单位置',
			dataIndex: 'orderLocation',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: number, record: any) => (
				<>
					{dict?.order_location?.map(
						(item: {dictKey: number; dictValue: string}) => {
							if (Number(item?.dictKey) === Number(text)) {
								return (
									<Tag color="processing" key={record?.id}>
										{item?.dictValue}
									</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '订单类型',
			dataIndex: 'orderType',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => (
				<>{text ? <Tag color="processing">{text}</Tag> : '--'}</>
			),
		},
		{
			title: '订单标签',
			dataIndex: 'orderLabel',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '订单号',
			dataIndex: 'orderNo',
			align: 'center',
			width: 300,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '车牌号',
			dataIndex: 'carNo',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <span>{text || '--'}</span>,
		},
		{
			title: '车型简称',
			dataIndex: 'brandName',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any, record: any) => (
				<>{`${record?.brandName ? record?.brandName : '--'}/${
					record?.modelName ? record?.modelName : '--'
				}`}</>
			),
		},
		{
			title: '网约车订单品类',
			dataIndex: 'orderCategory',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '提车日期',
			dataIndex: 'dateOfCollection',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: any) => (
				<>{text ? moment(text).format('YYYY-MM-DD') : '--'}</>
			),
		},
		{
			title: '考核期',
			dataIndex: 'periods',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <Tag color="processing">{text || '--'}</Tag>,
		},

		{
			title: '预计结束日期',
			dataIndex: 'estimatedEndDate',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: any) => (
				<>{text ? moment(text).format('YYYY-MM-DD') : '--'}</>
			),
		},
		{
			title: '订单实际结束日期',
			dataIndex: 'actualOrderEndDate',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: any) => (
				<>{text ? moment(text).format('YYYY-MM-DD') : '--'}</>
			),
		},
		{
			title: '押金（元）',
			dataIndex: 'deposit',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '首付（元）',
			dataIndex: 'downPayments',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '月租金（元）',
			dataIndex: 'monthlyRent',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '月服务费（元）',
			dataIndex: 'monthlyServiceFee',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '月总租金（租金+服务费）（元）',
			dataIndex: 'totalMonthlyRent',
			align: 'center',
			width: 250,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},

		{
			title: '尾款（元）',
			dataIndex: 'balancePayment',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '补贴方式',
			dataIndex: 'subsidyMode',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any, record: any) => (
				<>
					{Number(record?.subsidyMode) >= 0
						? dict?.subsidy_mode?.map(
								(item: {
									dictKey: number
									dictValue: string
								}) => {
									if (
										Number(item?.dictKey) ===
										Number(record?.subsidyMode)
									) {
										return (
											<Tag
												color="processing"
												key={record?.id}>
												{item?.dictValue}
											</Tag>
										)
									}
									return ''
								},
						  )
						: '--'}
				</>
			),
		},
		{
			title: '延租天数',
			dataIndex: 'daysOfExtension',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '金额（元）',
			dataIndex: 'moneyOfExtension',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '备注',
			dataIndex: 'remarks',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any, row: any) => (
				<>
					<Input
						placeholder="请输入备注"
						maxLength={30}
						defaultValue={text}
						onBlur={(e) => {
							e.persist()
							onOperationUpdate(row?.id, e.target.defaultValue)
						}}
					/>
				</>
			),
		},

		{
			title: '奖励生成时间',
			dataIndex: 'awardGenerationTime',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any) => <>{text || '--'}</>,
		},
		{
			title: '返现状态',
			dataIndex: 'cashBackDistribution',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any, row: any) => {
				if (Number(row.subsidyMode) === 3) {
					if (text && Number(text) > 0) {
						return (
							<Tag color="processing">
								{Number(text) === 1 ? '未返现' : '已返现'}
							</Tag>
						)
					}
					return <span>--</span>
				}
				return '--'
			},
		},
		{
			title: '发放状态',
			dataIndex: 'physicalDistribution',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any, row: any) => {
				if (Number(row.subsidyMode) !== 3) {
					if (text && Number(text) > 0) {
						return (
							<Tag color="processing">
								{Number(text) === 1 ? '未发放' : '已发放'}
							</Tag>
						)
					}
					return <span>--</span>
				}
				return '--'
			},
		},
		{
			title: '状态',
			dataIndex: 'status',
			align: 'center',
			width: 150,
			ellipsis: true,
			render: (text: any, record: any) => (
				<>
					{dict?.settlement_approval_status?.map(
						(item: {dictKey: number; dictValue: string}) => {
							if (
								Number(item?.dictKey) === Number(record?.status)
							) {
								return (
									<Tag color="processing" key={record?.id}>
										{item?.dictValue}
									</Tag>
								)
							}
							return ''
						},
					)}
				</>
			),
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 250,
			render: (text: any, record: any) => (
				<div>
					<Permissions permissionID="amc_merchantCenter_awardSettlement_processList_view">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname:
										'/merchantCenter/awardSettlement/processList/view',
									query: {
										id: record?.id,
										orgId:record.orgId,
										processId:record.processId,
									},
								})
							}}>
							详情
						</Button>
					</Permissions>
					{[0, 3, 5].includes(record?.status) ? (
						<Permissions permissionID="amc_merchantCenter_awardSettlement_processList_edit">
							<Button
								type="link"
								size="small"
								onClick={() => {
									history.push({
										pathname:
											'/merchantCenter/awardSettlement/processList/edit',
										query: {
											id: record.id,
										},
									})
								}}>
								编辑
							</Button>
						</Permissions>
					) : null}
					{record?.auditBut === 1 ? (
						<Permissions permissionID="amc_merchantCenter_awardSettlement_processList_process">
							<Button
								type="link"
								size="small"
								onClick={() => {
									history.push({
										pathname:
											'/merchantCenter/awardSettlement/processList/process',
										query: {
											id: record?.id,
											orgId:record.orgId,
											processId: record?.processId,
										},
									})
								}}>
								审核
							</Button>
						</Permissions>
					) : null}
					{record?.status === 4 ? (
						<Permissions permissionID="amc_merchantCenter_awardSettlement_processList_fee">
							<Button
								type="link"
								size="small"
								onClick={() => {
									history.push({
										pathname:
											'/merchantCenter/awardSettlement/processList/fee',
										query: {
											id: record?.id,
											commodityNo: record?.commodityNo,
										},
									})
								}}>
								补扣费审核
							</Button>
						</Permissions>
					) : null}
				</div>
			),
		},
	]

	// 初始化分页
	useEffect(() => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}, [searchData])

	// 搜索
	const onFinish = (values: any) => {
		const subsidyMonth = values?.subsidyMonth
			? formatDate(values?.subsidyMonth, 'YYYY-MM')
			: null
		const cityId = values?.city ? values?.city[1] : null
		const search = {
			...values,
			subsidyMonth,
			cityId,
		}
		delete search?.city
		setSearchData(search)
	}

	// 搜索重置
	const onReset = () => {
		setSearchData({})
	}
	useEffect(() => {
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'time',
						key: 'subsidyMonth',
						name: 'subsidyMonth',
						subtype: 'month',
						label: '补贴月份',
					},
					{
						type: 'cascader',
						label: '城市名称',
						name: 'city',
						key: 'city',
						fieldNames: {
							label: 'name',
							value: 'id',
							children: 'cityInfoList',
						},
						items: [...citysList],
					},
					{
						type: 'select',
						key: 'principalId',
						name: 'principalId',
						label: '主体名称',
						keys: 'id',
						title: 'name',
						items: [...mainCompany],
					},
				],
			},
			{
				type: 'group',
				key: 'group2',
				groupItems: [
					{
						type: 'select',
						key: 'orderLocation',
						name: 'orderLocation',
						label: '订单位置',
						showSearch: true,
						keys: 'dictKey',
						title: 'dictValue',
						items: [...dict.order_location],
					},
					{
						type: 'select',
						key: 'orderType',
						name: 'orderType',
						label: '订单类型',
						keys: 'code',
						title: 'name',
						items: [...orderType],
					},
					{
						type: 'input',
						key: 'orderNo',
						name: 'orderNo',
						label: '订单号',
					},
				],
			},
			{
				type: 'group',
				key: 'group3',
				groupItems: [
					{
						type: 'treeSelect',
						label: '所属公司',
						name: 'companyId',
						key: 'companyId',
						keys: 'id',
						title: 'name',
						treeData: [...orgSource],
					},
					{
						type: 'input',
						name: 'driverName',
						key: 'driverName',
						label: '司机姓名',
					},
					{
						type: 'input',
						name: 'carNo',
						key: 'carNo',
						label: '车牌号',
					},
				],
			},
			{
				type: 'group',
				key: 'group4',
				groupItems: [
					{
						type: 'select',
						key: 'status',
						name: 'status',
						label: '状态',
						keys: 'dictKey',
						title: 'dictValue',
						items: [...dict.settlement_approval_status],
					},
					{
						type: 'select',
						key: 'physicalDistribution',
						name: 'physicalDistribution',
						label: '实物发放状态',
						keys: 'dictKey',
						title: 'dictValue',
						items: [...dict.physical_state],
					},
					{
						type: 'time',
						key: 'awardGenerationTime',
						name: 'awardGenerationTime',
						subtype: 'date',
						label: '奖励生成日期',
					},
				],
			},
		]
		setFormData(formItems)
	}, [citysList, orgSource, orderType, dict, mainCompany])

	// 关闭弹窗
	const onCancel = () => {
		setIsModalBackOpen(false)
		setIsModalIssuedOpen(false)
	}
	// 批量返现
	const onSubmitBack = () => {
		const ids = checkData.map((item: any) => item?.id)
		postCashBackDistribution({ids})
			.then((res: any) => {
				if (res?.success) {
					message.success(res?.msg)
					setIsModalBackOpen(false)
					onListFun()
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}
	// 批量已发放
	const onSubmitIssued = () => {
		const ids = checkData?.map((item: any) => item?.id)
		postPhysicalDistribution({ids})
			.then((res: any) => {
				if (res?.success) {
					message.success(res?.msg)
					setIsModalIssuedOpen(false)
					onListFun()
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}

	const onCancelToExamineView = () => {
		toExamineForm.resetFields()
		setIsToExamineView(() => false)
	}

	// 批量（含单个）审核
	const onBatchApproval = async () => {
		const toExamineFormData = await toExamineForm.validateFields()
		const ids = checkProcessList?.map((item: any) => item?.id)
		batchApproval({ids, ...toExamineFormData})
			.then((res: any) => {
				if (res?.success) {
					message.success(res?.msg)
					setIsToExamineView(false)
					onListFun()
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}
	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="btnlist">
				<Space size={12}>
					<Permissions permissionID="amc_merchantCenter_awardSettlement_processList_cash">
						<Button
							ghost
							size="small"
							type="primary"
							disabled={!checkData?.length}
							onClick={() => {
								setIsModalBackOpen(true)
							}}>
							批量设置为已返现
						</Button>
					</Permissions>
					<Permissions permissionID="amc_merchantCenter_awardSettlement_processList_grant">
						<Button
							type="primary"
							ghost
							size="small"
							disabled={!checkData?.length}
							onClick={() => {
								setIsModalIssuedOpen(true)
							}}>
							批量设置为已发放
						</Button>
					</Permissions>
					<Permissions permissionID="amc_merchantCenter_awardSettlement_processList_process">
						<Button
							ghost
							size="small"
							type="primary"
							disabled={!checkProcessList?.length}
							onClick={() => {
								setIsToExamineView(() => true)
							}}>
							批量审核
						</Button>
					</Permissions>
				</Space>
			</div>
			<div className="table">
				<CustomTable
					params={params}
					columns={columns}
					pagination
					kid="id"
					total={total}
					scroll={{y: 500}}
					showRowSelection
					selectCallback={(keys: any, selectData: any) => {
						const processList = selectData.filter(
							(item: any) => item?.auditBut === 1,
						)
						setCheckProcessList(() => processList)
						setCheckData(() => selectData)
					}}
					getCheckboxProps={{
						getCheckboxProps: (record: any) => {
							if (
								(record?.cashBackDistribution === 2 ||
									record?.physicalDistribution === 2) &&
								record.status === 2
							) {
								return {disabled: true}
							}
							return null
						},
					}}
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataSourse}
				/>
			</div>
			<ModalComponent
				title="批量置为已返现"
				text="确定要将已选择的司机结算中的返现奖励的状态置为已返现吗？"
				onSubmit={onSubmitBack}
				onCancel={onCancel}
				isModalOpen={isModalBackOpen}
				setIsModalOpen={setIsModalBackOpen}
			/>
			<ModalComponent
				title="批量置为已发放"
				text="确定要将已选择的司机结算中的实物奖励的状态置为已发放吗？"
				onSubmit={onSubmitIssued}
				onCancel={onCancel}
				isModalOpen={isModalIssuedOpen}
				setIsModalOpen={setIsModalIssuedOpen}
			/>
			<Modal
				title="批量审核商品方案"
				open={isToExamineView}
				onCancel={onCancelToExamineView}
				width="600px"
				destroyOnClose
				footer={
					<>
						<Button
							size="small"
							type="primary"
							onClick={onBatchApproval}>
							确定
						</Button>
						<Button size="small" onClick={onCancelToExamineView}>
							取消
						</Button>
					</>
				}>
				<>
					<Form
						form={toExamineForm}
						name="basic"
						layout="horizontal"
						labelCol={{flex: '100px'}}
						labelAlign="right"
						labelWrap
						initialValues={{remember: true}}
						autoComplete="off">
						<Row gutter={12}>
							<Col sm={{span: 24}}>
								<Form.Item
									label="审核状态"
									name="pass"
									rules={[
										{
											required: true,
											message: '请选择审核状态',
										},
									]}>
									<Radio.Group>
										<Radio value={1}>审核通过</Radio>
										<Radio value={2}>审核驳回</Radio>
									</Radio.Group>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}}>
								<Form.Item label="处理意见" name="message">
									<TextArea
										maxLength={200}
										placeholder="请填写处理意见，不超过200个字符"
										autoSize={{
											minRows: 3,
											maxRows: 6,
										}}
									/>
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</>
			</Modal>
		</div>
	)
}
export default connect(({user}: any) => ({
	user,
}))(commodityPlan)
